iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0
Python

用 Python 打造你的 Discord BOT系列 第 7

[Day 07] 觸發條件 (二):指令 ── slash command

  • 分享至 

  • xImage
  •  

今天開始介紹第二種觸發條件:指令。

進度

在 Discord,互動 (interaction) 是一個重要的特色,甚至文件中有特別把互動做一個整理。互動一共有三種:

  1. 指令 (Commmand):可以跟 Discord 應用互動的原生方式
  2. 訊息元件 (Message Component):可以在放在訊息中的互動式元件,例如:按鈕
  3. 互動視窗 (Modal):可以讓使用者填入資料的彈出視窗

不過,在這個系列的文章,我傾向把「指令」歸類到「觸發條件」中,「訊息元件」與「互動視窗」則是歸類到「執行內容」。

今天會先介紹其中一種指令:slash command。

什麼是指令?

有的地方翻做「命令」,就連 Discord 的 Developer Help Center 的翻譯也沒有統一...

指令只是一個簡稱,完整一點應該稱呼為「應用指令 (Application Commands)」,它可以讓使用者用很簡單、直觀的方式對 Discord BOT 下達要求。

指令一共有三種:

  1. 斜線指令 (slash command)
  2. 訊息指令 (message command)
  3. 用戶指令 (user command)

不過,其實現在應該有四種,在 2024-08-26 公告了第四種指令:Entry Point command,與 Discord 的活動 (Activity) 有關,但這系列就不介紹了

Entry Point command 超級新,新到連 Discord 官方文件內文還是寫三種 (儘管下面列了四種 XD)

什麼是斜線指令 (slash command)?

如上面所述,斜線指令的使用方式非常簡單,只要在輸入框輸入一個斜線 (/) 就可以看到一個指令選單,接下來只要點擊選擇想要使用的功能就好。當然,如果記得指令的話,也可以直接輸入完整指令。

第一個斜線指令

1. 取得伺服器 ID

在開發斜線指令之前,要先取得伺服器 ID (guild ID),這邊提供兩種簡單的取得方法。

從 Discord 上取得

伺服器 ID 可以直接從 Discord 拿到,但需要開啟開發者模式。而開啟的方法如下:

點擊左下方自己的名稱旁的齒輪按鈕,開啟使用者設定。

進入進階分頁

開啟開發者模式

接下來,回到伺服器,對著伺服器名稱按滑鼠右鍵,就會出現一個選單,點擊「複製伺服器 ID」即可。

用 discord.py 取得

這個方法也很簡單,讓程式取得並印出來就好。只要把之前的 Quickstart 程式調整一下就好:

@client.event
async def on_ready():
    print("guilds", client.guilds[0].id)

2. 確認權限

權限的部分其實已經有了,只是想要給大家確認一下~

在加入伺服器的時候 (Day 02),其實就有特別列出請求授予 Discord BOT 「應用指令」的權限:

另外,之前在查看 Discord BOT 權限時 (Day 05),有一個權限清單,裡面也有列到「使用應用程式命令」:

3. 撰寫程式

先使用這個範例 (簡化自 Github 上的範例)

# day07.py

import discord
from discord import app_commands

GUILD_ID = "your guild ID"
MY_GUILD = discord.Object(id=GUILD_ID)


class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)


intents = discord.Intents.default()
client = MyClient(intents=intents)


@client.event
async def on_ready():
    print(f'Logged in as {client.user} (ID: {client.user.id})')


@client.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')

client.run('token')

4. 完成

執行之後,來測試一下結果。

  1. 在對話框輸入一個斜線 (/),可以看到多了一個 /hello

    /hello 下方有一個小小的說明:Says hello!,右邊顯示這是來自我們的 Discord BOT 的斜線指令。

  2. 左鍵點選後,就會帶入完整指令 /hello

  3. 按下 Enter 送出訊息之後,就可以看到

    畫面中會顯示哪位成員使用了哪個指令,並且成功觸發我們寫好的功能:Tag 成員。

解釋程式碼

最後,來了解一下範例程式的內容。以下會挑幾個片段進行說明:

  1. 建立自己的 Client Class

    class MyClient(discord.Client):
        def __init__(self, *, intents: discord.Intents):
            super().__init__(intents=intents)
            self.tree = app_commands.CommandTree(self)
    
        async def setup_hook(self):
            self.tree.copy_global_to(guild=MY_GUILD)
            await self.tree.sync(guild=MY_GUILD)
    
    • 這種寫法前面 (day 04) 也有看過,只是 override 的是事件,不是這邊的 setup_hook
    • CommandTree 是 application command 的容器,要先建立一個容器來乘載自訂的斜線指令
      self.tree = app_commands.CommandTree(self)
      
    • setup_hook 中,把後面的斜線指令同步到指定的伺服器內 (不指定的話,註冊斜線指令要等很久)
  2. 斜線指令

    @client.tree.command()
    async def hello(interaction: discord.Interaction):
        """Says hello!"""
        await interaction.response.send_message(f'Hi, {interaction.user.mention}')
    
    • 這就是斜線指令的內容,由於函數名稱為 hello,所以觸發的指令就是 /hello,而下方的註解 (Says hello!) 就會成為指令說明。

礙於時間篇幅,今天就先介紹到這邊了,還有一些 slash command 更進階的用法還沒介紹,預計等到所有應用指令都介紹完,再回頭一起介紹。
/images/emoticon/emoticon06.gif

小結

今天我們介紹了斜線指令 (slash command),明天會繼續介紹其他應用指令~


上一篇
[Day 06] 觸發條件 (一):事件
下一篇
[Day 08] 觸發條件 (三):指令 ── message command 與 user command
系列文
用 Python 打造你的 Discord BOT14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
idea-stu
iT邦新手 5 級 ‧ 2024-09-26 15:11:44

目前也正在學習怎麼製作 discordbot,謝謝作者的教學

ck642509 iT邦新手 4 級 ‧ 2024-09-26 23:41:59 檢舉

不會~ 大家可以互相交流,一起學習XD

稍早有看到有提問,但因為要趕稿,現在才有辦法回應,看起來問題已經解決了?

我要留言

立即登入留言